<template>
    <div>
        <van-tabs v-model:active="active">

            <van-tab title="短信验证码登录">
                <van-cell-group inset>
                    <van-field v-model="val.tel" type="tel" label="手机号" placeholder="请输入手机号" />
                    <van-field v-model="val.sms" center clearable label="短信验证码" placeholder="请输入短信验证码">
                        <template #button>
                            <van-button size="small" type="primary" @click="handleClickYzm">{{ val.countTitle
                                }}</van-button>
                        </template>
                    </van-field>
                </van-cell-group>
            </van-tab>
            <van-tab title="账号密码登录">
                <van-form @submit="onSubmit">
                    <van-cell-group inset>
                        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                            :rules="[{ required: true, message: '请填写用户名' }]" />
                        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                            :rules="[{ required: true, message: '请填写密码' }]" />
                    </van-cell-group>
                    <div style="margin: 16px;">
                        <van-button round block type="primary" native-type="submit">
                            提交
                        </van-button>
                    </div>
                </van-form>

            </van-tab>
        </van-tabs>

    </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()

const active = ref(0);
const username = ref('');
const password = ref('');

const val = reactive({
    tel: '',
    sms: '',
    countTimes: 10,
    countTitle: '发送验证码',
    timer: null,
})

const onSubmit = (values) => {
    // 本地存储
    localStorage.setItem('username', username.value)

    // 登录成功就跳转页面
    setTimeout(()=>{
        router.push({
            path: '/'
        })
    }, 1000)
};

const handleClickYzm = () => {
    // 开启定时器
    val.timer = setInterval(() => {
        val.countTimes--
        val.countTitle = '倒计时' + val.countTimes
        // 倒计时结束时
        if (val.countTimes === 0) {
            // 清除定时器
            clearInterval(val.timer)
            // 重新赋值时长
            val.countTimes = 10
            // 按钮文字内容
            val.countTitle = '重新获取验证码'

            // 生成数随机验证码
            const maxVal = 999999
            const minVal = 100000
            val.sms = Math.floor(Math.random() * (maxVal - minVal + 1)) + 1
        }
    }, 1000)
}

</script>